package com.zxj.test.service;

import java.util.Objects;
import java.util.Random;

import com.zxj.test.model.SmsResult;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

/**
 * @author zxj
 * @date 2020/7/18
 */
@Service
public class SmsService {

    @Autowired
    private RestTemplate restTemplate;

    private static final String REQUEST_URL = "http://feginesms.market.alicloudapi.com/codeNotice";
    private static final String APP_CODE = "3c70803803da4276a990821e5815164b";

    private static final String MOBILE_PATTERN = "0?(13|14|15|17|18|19)[0-9]{9}";

    public boolean sendVerificationCode(String mobile) {
        if (StringUtils.hasText(mobile) && !mobile.matches(MOBILE_PATTERN)) {
            throw new IllegalArgumentException("手机号格式不正确");
        }

        int min = 100000;
        int max = 1000000;
        int code = min + new Random().nextInt(max) % (max - min + 1);

        MultiValueMap<String, String> requestParameters = new LinkedMultiValueMap<>(8);
        requestParameters.add("sign", String.valueOf(1));
        requestParameters.add("skin", String.valueOf(1));
        requestParameters.add("param", String.valueOf(code));
        requestParameters.add("phone", mobile);

        UriComponents components = UriComponentsBuilder.fromUriString(REQUEST_URL)
                .queryParams(requestParameters)
                .build();

        RequestEntity<Void> requestEntity = RequestEntity.get(components.toUri())
                .header("Authorization", "APPCODE " + APP_CODE)
                .build();

        ResponseEntity<SmsResult> responseEntity = restTemplate.exchange(requestEntity, SmsResult.class);

        SmsResult result = responseEntity.getBody();

        return "OK".equals(Objects.requireNonNull(result).getCode());
    }
}
